package com.cloudkinto.utils;

import com.alibaba.fastjson.JSON;
import com.cloudkinto.utils.amazon.AmazonUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import springfox.documentation.spring.web.json.Json;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.cloudkinto.common.utils.OkHttpUtils.getUnsafeOkHttpClient;

@Slf4j
public class YahooUtils {
    public static final String clientIdV1 = "dj00aiZpPU1wcG9yTlFBSlFQcSZzPWNvbnN1bWVyc2VjcmV0Jng9YzA-";
    public static final String clientSecretV1 = "GBvs8lGmUPdhKsbniiuET3aRP048tOJGYzFie4kX";

    public static final String clientIdV2 = "dj00aiZpPTR4TWV0WnBqT1dWTyZzPWNvbnN1bWVyc2VjcmV0Jng9NDI-";
    public static final String clientSecretV2 = "0yJ9T5VBjxKPQDbL2RgL1YK645PBNHtsF7oEXNX4";


    public static String yahooDoGet(String serviceUrl, String accessToken, Map parametersMap) throws Exception {
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Authorization", "Bearer " + accessToken);//验证 eBay 市场帐户删除/关闭通知实际上来自 eBay 时，Authorization = Bearer +accessToken
        headerMap.put("content-type", "application/json; charset=utf-8");
        if (parametersMap.size() > 0)
            serviceUrl = serviceUrl + "?" + AmazonUtil.sortParams(parametersMap);
        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 1081);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
        OkHttpClient.Builder builder = getUnsafeOkHttpClient().newBuilder();
        builder.connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
//                .proxy(proxy)
                .retryOnConnectionFailure(false);
        Request.Builder requestBuilder = AmazonUtil.createSPHeader(headerMap);
        Request request = requestBuilder.url(serviceUrl).get().build();
        Response response = null;
        String body = "";
        response = builder.build().newCall(request).execute();
        body = response.body().string();
        log.debug(body);
        return body;
    }


    public static String getBase64ESA(String clientId, String clientSecret) {
        byte[] pass = (clientId.trim() + ":" + clientSecret.trim()).getBytes(StandardCharsets.UTF_8);
        return "Basic " + Base64.getEncoder().encodeToString(pass);
    }

    /**
     * 获取刷新令牌
     *
     * @param serviceUrl
     * @param param
     * @return
     * @throws Exception
     */
    public static String yahooDoPost(String serviceUrl, Map<String, String> param) throws Exception {
        return yahooDoPost(serviceUrl, getBase64ESA(clientIdV2, clientSecretV2), "application/x-www-form-urlencoded", param);
    }

    public static String yahooDoPost(String serviceUrl, String accessToken, Map<String, String> param) throws Exception {
        return yahooDoPost(serviceUrl, "Bearer " + accessToken, "application/json", param);
    }

    public static String yahooDoPost(String serviceUrl, String accessToken, String param) throws Exception {
        return yahooDoPost(serviceUrl, "Bearer " + accessToken, "application/xml", param);
    }

    public static String yahooDoPost(String serviceUrl, String authorization, String contentType, Map<String, String> param) throws Exception {
        Response response = yahooDoPostUtils(serviceUrl, authorization, contentType, param);
        String body = "";
        body = response.body().string();
        log.debug(body);
        return body;
    }

    public static String yahooDoPost(String serviceUrl, String authorization, String contentType, String param) throws Exception {
        Response response = yahooDoPostUtils(serviceUrl, authorization, contentType, param);
        String body = "";
        body = response.body().string();
        log.debug(body);
        return body;
    }

    /**
     * 表单格式上传xxx-from
     *
     * @param serviceUrl
     * @param authorization
     * @param contentType
     * @param param
     * @return
     * @throws Exception
     */
    public static Response yahooDoPostUtils(String serviceUrl, String authorization, String contentType, Map<String, String> param) throws Exception {
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Authorization", authorization);//Authorization -> 生产：
        headerMap.put("Content-type", contentType); //获取客户端AccessToken 需要设置

        OkHttpClient client = getUnsafeOkHttpClient();
        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 1081);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
        OkHttpClient.Builder builder = client.newBuilder();
        builder.connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
//                .proxy(proxy)
                .retryOnConnectionFailure(false);
        Request.Builder requestBuilder = AmazonUtil.createSPHeader(headerMap);
        log.debug(JSON.toJSONString(param));
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        if (param != null && !param.isEmpty()) {
            for (String key : param.keySet()) {
                formBodyBuilder.add(key, param.get(key));
            }
        }
        Request request = requestBuilder.url(serviceUrl)
                .post(formBodyBuilder.build())
                .build();
        Response response = null;
        response = client.newCall(request).execute();
        return response;
    }

    /**
     * xml格式上传
     *
     * @param serviceUrl
     * @param authorization
     * @param contentType
     * @param param
     * @return
     * @throws Exception
     */
    public static Response yahooDoPostUtils(String serviceUrl, String authorization, String contentType, String param) throws Exception {
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Authorization", authorization);//Authorization -> 生产：
        headerMap.put("Content-type", contentType); //获取客户端AccessToken 需要设置

        OkHttpClient client = getUnsafeOkHttpClient();
        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 1081);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
        OkHttpClient.Builder builder = client.newBuilder();
        builder.connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
//                .proxy(proxy)
                .retryOnConnectionFailure(true);
        Request.Builder requestBuilder = AmazonUtil.createSPHeader(headerMap);
        Request request = requestBuilder.url(serviceUrl)
                .post(RequestBody.create(MediaType.parse(contentType), param))
                .build();
        log.debug(JSON.toJSONString(param));
        Response response = null;
        response = client.newCall(request).execute();
        return response;
    }

}
